package br.usp.ime.origami.primitives;

import java.awt.geom.Line2D;
import java.util.List;

import org.apache.log4j.Logger;

import br.usp.ime.origami.model.Point;

public class TriangulationPrimitives
{

	private static Logger logger = Logger.getLogger(TriangulationPrimitives.class);
	
	public static boolean isEar(int x, List<? extends Point> points) {
	
		Point begin = points.get((x - 1 + points.size()) % points.size());
	
		Point end = points.get((x + 1) % points.size());
	
		// cant intersect with any edge
		for (int i = 0; i < points.size(); i++) {
	
			Point first = points.get(i);
			Point next = points.get((i + 1) % points.size());
	
			if (first.equals(begin) || first.equals(end) || next.equals(begin) || next.equals(end)) {
				continue;
			}
	
			logger.debug(String.format("testing %d: (%s-%s) intersects (%s-%s) ", i, begin, end, first, next));
			if (Line2D.linesIntersect(begin.getX(), begin.getY(), end.getX(), end.getY(), first.getX(), first.getY(),
					next.getX(), next.getY())) {
	
				logger.info(String.format("TRUE "));
				return false;
			}
		}
	
		// must be incone (orourke page 37)
		Point ear = points.get(x);
		Point beforeBegin = points.get((x - 2 + points.size()) % points.size());
		return isSegmentBetweenAngle(begin, end, beforeBegin, ear);
	}

	/**
	 * returns if p1->p3 between p1->p2 and p1->p4. see incone (orourke page
	 * 37);
	 * 
	 */
	private static boolean isSegmentBetweenAngle(Point i, Point j, Point i1, Point im1) {
		logger.debug(String.format("is %s-%s between (%s-%s) and (%s-%s) ", i, j, i, im1, i, i1));
		// convex :
		if (BasicPrimitives.leftOn(im1, i, i1)) {
			return BasicPrimitives.left(i, j, im1) && BasicPrimitives.left(j, i, i1);
		}
	
		// reflex:
		return !(BasicPrimitives.leftOn(i, j, i1) && BasicPrimitives.leftOn(j, i, im1));
	}

}
